"""
    Computational Economics
    2.7: Object-Oriented Programming in Python
    http://johnstachurski.net/lectures/oop.html

    DEFINITIONS
    Cumulative Distribution Function
    "Intuitively, it is the 'area so far' function of the probability
    distribution. Cumulative distribution functions are also used to specify
    the distribution of multivariate random variables."

    REFERENCES
    http://en.wikipedia.org/wiki/Glivenko%E2%80%93Cantelli_theorem
    http://en.wikipedia.org/wiki/Cumulative_distribution_function
"""

from __future__ import division
from random import uniform


class EmpiricalDistributionFunction:

    observations = []

    def __init__(self, samples=[]):
        self.observations = samples

    def __call__(self, x):
        return self.evaluate(x)

    def evaluate(self, x):
        y = 0
        n = len(self.observations)
        for X in self.observations:
            if X <= x:
                y += 1
        return (1.0 / n ) * y

    def stachurski(self, x):
        counter = 0.0
        for obs in self.observations:
            if obs <= x:
                counter += 1
        return counter / len(self.observations)



def main():
    samples = [uniform(0, 1) for i in range(10)]
    f = EmpiricalDistributionFunction(samples)
    r = f(0.5)
    s = f.stachurski(0.5)
    print r, s
    mag = min([len(str(n).split('.')[1]) for n in (r, s)])
    assert round(r, mag) == round(s, mag)

    f.observations = [uniform(0, 1) for i in range(1000)]
    r = f(0.5)
    s = f.stachurski(0.5)
    print r, s
    mag = min([len(str(n).split('.')[1]) for n in (r, s)])
    assert round(r, mag) == round(s, mag)


#
# MAIN
#
if __name__ == "__main__":
    main()
    print '%s: ok' % (__file__)
